package test.countchars;

public class Solution {
    public int countCharacters(String[] words, String chars) {
//        输入：words = ["hello","world","leetcode"], chars = "welldonehoneyr"
//        输出：10
//        解释：
//        可以形成字符串 "hello" 和 "world"，所以答案是 5 + 5 = 10。
//        1 <= words.length <= 1000
//        1 <= words[i].length, chars.length <= 100
//        所有字符串中都仅包含小写英文字母

        final int n = 26;
        int[] charsNum = count(chars, n);
        int result = 0;
        for (String word : words) {
            int[] wordNum = count(word, n);
            if (contains(charsNum, wordNum)) {
                result += word.length();
            }
        }
        return result;
    }

    private boolean contains(int[] charsNum, int[] wordNum) {
        for (int j = 0; j < wordNum.length; j++) {
            if (wordNum[j] > charsNum[j]) {
                return false;
            }
        }
        return true;
    }


    private int[] count(String chars, int n) {
        int[] charNums = new int[n];
        for (int i = 0; i < chars.length(); i++) {
            charNums[chars.charAt(i) - 97]++;
        }
        return charNums;
    }
}
